<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Shijue_weibo extends CI_Controller {
	var $MAX_RENUM = 30;//最大重复次数
	var $SEND_DATA = false;//404页面检查开关
	var $CHECK_NOT_FOUND = false;//发送数据开关（调试用）
	
	public function __construct() {
        	parent::__construct();
		$this->load->model('queue_model');
    	}

	public function post_weibo(){
		if(!$_POST['cookie']){
		     	echo "<script>alert('cookie不能为空~');window.history.back(-1);</script>";
		 	return false;
		}
		$data['username'] = $this->session->userdata('username');
		$rs['cookie'] = trim($_POST['cookie']);
		$rs['time'] = time();
		$res = $this->db->insert('cookies',$rs);
		if($res){
			$time = time();
                	$yes_time = time() - 86400;
			$res = "SELECT * from cookies where time <".$time." and time >".$yes_time;
                	$count =$this->db->query($res);
                	$count =$count->result_array();
                	//print_r($count);die;
                	$data['count'] = count($count);
			echo "<script>alert('添加成功');</script>";
			redirect('shijue_weibo/weibo');
		}else{
			echo "<script>alert('添加失败~');window.history.back(-1);</script>";
		}
		
	}
	public function weibo(){
		$time = time();
		$yes_time = time() - 86400;
		$res = "SELECT * from cookies where time <".$time." and time >".$yes_time;
		$count =$this->db->query($res);
        	$count =$count->result_array();
		//print_r($count);die;
        	$data['count'] = count($count);
		$data['username'] = $this->session->userdata('username');
		$this->load->view('weibo',$data);
	}


	public function weibo_addtask(){
		$this->load->model('queue_model');	
		$res = "SELECT * from shijue_project_new where clue_type = 3 and status = 2 limit 100";
		$count =$this->db->query($res);
        	$data =$count->result_array();
        	$rs_status = false;
        	foreach ($data as $v) {
        		$rs = array();
        		$rs['task_id'] = $v['task_id'];
        		$rs['clue_id'] = $v['clue_id'];
        		$rs['company_id'] = $v['company_id'];
        		$rs['uid'] = $v['biz'];
			$rs['id'] = $v['id'];
        		$rs_status = $this->queue_model->add_weibo_task($rs);
			
			if($rs_status){
				$r = true;
			}
			if($r){
				echo "ok";
			}else{
				echo "no";
			}
       	 	}


	}


//=================================================================================================
	public function startTask(){
		if(false == ($json_keyword = $this->queue_model->get_weibo_task())){
			sleep(3);
			return false;		
		}
		$get_list = json_decode($json_keyword,true);
		$id = $get_list['id'];
		$uid = $get_list['uid'];
		$task = $get_list['task_id'];
		$clue = $get_list['clue_id'];
		$company_id = $get_list['company_id'];
    		$j = 0;
    		$renum = 0;
   		$re_sleep_num = 0;
    		$re_totalisnull_num = 0;
    		$remax = $this->MAX_RENUM;
    		$last_p = 0;
    		$not_found_num = 0;
    		$total_num = 0;
    		$total_data = 0;
    		$return_msg = array();
    		$p = 1;
    		while ($p<4000){
        		if($p == $last_p){
            		$renum++;
        	}else{
            		$renum = 0;
            		$re_sleep_num = 0;
            		$re_totalisnull_num = 0;
            		echo "\n++ ".$p ." ++\n";
        	}
        
        	if($re_sleep_num == $remax){
            		$return_msg[0] = $not_found_num;
            		$return_msg[1] = "Sleep 1";
            		$return_msg[2] = $total_num;
            		$return_msg[3] = $total_data;
            		return $return_msg;
        	}
            
        	if($re_totalisnull_num == $remax){
            		$return_msg[0] = $not_found_num;
            		$return_msg[1] = "Total is null";
            		$return_msg[2] = $total_num;
            		$return_msg[3] = $total_data;
            		return $return_msg;
        	}

        	if($renum == $remax){
            		$return_msg[0] = $not_found_num;
            		$return_msg[1] = "Success";
            		$return_msg[2] = $total_num;
            		$return_msg[3] = $total_data;
	    		$update_clue = 'http://eagle.elephant.vcg.com/api/spider-update-clue';
	    		$clue_info = array(
			'task_id' => $task,
			'clue_id' => $clue,
			'status' => 3
	     		);
	    		$clue_status = $this->post_data($update_clue,$clue_info);
			$weibo_data['status'] = 4;
			$rs = $this->db->where('id',$id)->update('shijue_project_new',$weibo_data);
            		return $return_msg;
        	}
	    	$uid = trim($uid);
        	$url = "https://m.weibo.cn/container/getIndex?type=uid&containerid=107603{$uid}&page=" . $p;
        	$page = $this->send_http($url);
        	if($page == false){
            		echo "[ sleep 1 ]";
            		$re_sleep_num++;
            		$last_p = $p;
            		sleep(1);
            		continue;
        	}
        
        	$result = json_decode($page, true);
        	if(empty($result['cardlistInfo']['total'])){
            		echo "[ total is null ]";
            		sleep(1);
            		$re_totalisnull_num++;
            		$last_p = $p;
            		continue;
        	}
        
        	$last_p = $p;
        
        	// print_r($result);exit;
        	if (! empty ( $result['cards'] ) && isset ( $result ['cards'] )) {
            		$cards = $result ['cards'];

            		foreach ($cards as $val){
                		$card_group = $val;
    
                		if (empty ( $card_group ) || (! isset ( $card_group ['mblog'] ))) {
                    			continue;
                		}
    
                		$mblog = $card_group ['mblog'];

                		$current_data = array();
                		// 时间
                		$current_data ['ctime'] =$this->get_time($mblog ['created_at']);
                
                		$a['url_article'] = strip_tags($mblog ['text']);
                		$a['url_article_title'] = '新浪微博';

                		// 连接
                		$current_data ['url'] = "http://weibo.com/".$mblog['user']['id']."/".$mblog['bid'];
                
                		//检测页面是否为404
                		if ($this->CHECK_NOT_FOUND){
                    			if(is404page($current_data ['url'])){
                        			echo "++404 Not Found++";
                        			$not_found_num++;
                        			continue;   
                    			}
                		}
                
                		if( isset($mblog ['pics']) && $mblog ['pics']){
                    		$pics = $mblog ['pics'];
                    		echo "[ ";
                    		foreach ($pics as $pic){
                        		$total_num ++;
                        		//$current_data ['pics'] [] = $pic['url'];
                        		$a['pid'] =time().rand(10000,100000);
                        		$a['task_id'] =$task;
                        		$a['clue_id'] =$clue;
			            	$a['company_id'] = $company_id;
                        		$a['is_cover'] =0;
                        		$a['client_date'] =$current_data['ctime'];
                        		$a['url'] =$current_data['url'];
                        		$a['pic_url'] =$pic['url'];
                        		print_r($a);
                        		//echo $pic['url'];
                        		//echo "\n";
                        		if ($this->SEND_DATA){
                            			$post = json_encode($a,true);

                            			$post ='['.$post.']';
                            
                            			$url="http://shijue.qingapi.cn/task/start";
                            			$pro = send_http_data($url, array('resource'=>$post));
                            
                           			if($pro == "ok"){
                                			echo $pro;
                                			$total_data++;
                            			}
      
     	                       		else{
                                		echo "null";
                            		}
                            			$j ++;
                            			echo ", ";
                        		}
                    		}
                    			echo " ]";
                		}
            		}
        	}
        	else	
            		continue;
        		$p ++;
        		sleep(1);
    	}

    		echo $j;
    		$return_msg[0] = $not_found_num;
    		$return_msg[1] = "To Page Limit (".$j.")";
    		$return_msg[2] = $total_num;
    		$return_msg[3] = $total_data;
    		return $return_msg;
	}
//=================================================================================================


	function get_cookie(){
		$rs = "select * from cookies order by rand() LIMIT 1";
		$dd =$this->db->query($rs);
                $data =$dd->result_array();
		$rs = $data[0]['cookie'];
		return $rs;
	}
	function send_http($url, $post = array(), $ip = "", $timeout = 15, $header = array(), $connecttimeout = 15) {

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/20100101 Firefox/50.0');
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

		//$cookie = COOKIE;
		//var_dump($cookie);
		curl_setopt($ch, CURLOPT_COOKIE, $this->get_cookie());
		if($post){
			if(is_array($post)){
			$post = http_build_query($post);
		}

		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
		}	

		if ($header){
			curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		}
		if(!empty($ip)) {
			curl_setopt($ch, CURLOPT_PROXY, $ip);
			curl_setopt($ch, CURLOPT_PROXYTYPE , CURLPROXY_SOCKS5);
			curl_setopt($ch, CURLOPT_PROXYUSERPWD, "hongmai:soften.cn");
		}

		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); 
		$rs = curl_exec($ch);
		$http_info = curl_getinfo($ch);
		//print_r($http_info);
		curl_close($ch);
		if($http_info['http_code'] != 200 && $http_info['http_code'] != 302 ){
			//print_r($http_info);
			return false;
		}
		return $rs;
	}

//===============================================	
	function send_http_data($url, $post = array(), $ip = "", $timeout = 10, $header = array(), $connecttimeout = 60) {

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:19.0) Gecko/20100101 Firefox/19.0');
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

		if($post){
			if(is_array($post)){
			$post = http_build_query($post);
			}

			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
		}

		if ($header){
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		}
		if(!empty($ip)) {
			curl_setopt($ch, CURLOPT_PROXY, $ip);
			curl_setopt($ch, CURLOPT_PROXYTYPE , CURLPROXY_SOCKS5);
			curl_setopt($ch, CURLOPT_PROXYUSERPWD, "hongmai:soften.cn");
		}

		//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); 
		$rs = curl_exec($ch);
		$http_info = curl_getinfo($ch);

		curl_close($ch);
		if($http_info['http_code'] != 200 && $http_info['http_code'] != 302 ){
			return false;
		}
		return $rs;
	}
function post_data($url, $post_data = '', $timeout = 5){  
        $ch = curl_init();  
        curl_setopt ($ch, CURLOPT_URL, $url);  
        curl_setopt ($ch, CURLOPT_POST, 1);  
        if($post_data != ''){  
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);  
        }  
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);   
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);  
        curl_setopt($ch, CURLOPT_HEADER, false);  
        $file_contents = curl_exec($ch);  
        curl_close($ch);  
        return $file_contents;  
    }  


	function get_time($str){
		date_default_timezone_set('Asia/Shanghai'); 
		if( preg_match("/(\d+)-(\d+)-(\d+) (\d+):(\d+)/", $str, $out)) {

		return $str;
		}
		if( preg_match("/^(今天|昨天|前天) (\d+):(\d+)/", $str, $out)) {
			if( $out[1] == '今天' ) {
			return $time = date('Y-m-d' , time()).' '.$out[2].':'.$out[3];
			}
		}
		if( preg_match("/(\d+)-(\d+) (\d+):(\d+)/", $str, $out)) {

			return $time = '2017-'.$out[0];
		}
		if( preg_match("/(\d+)-(\d+)/", $str, $out)) {
            	$t = time();
            	$i = date("m",$t);
            	//echo $i;
            		if($out[1] > $i){
                    		return $time = '2016-'.$out[0];
            		}else{
                    		return $time = '2017-'.$out[0];
            		}
		}

		if( preg_match("/(\d+)(分钟前)/", $str, $out)) {

			return $time = date('Y-m-d H:i:s' , time()-60*$out[1]);
		}
	}





}
